package cn.superchart.common.utils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestContextUtil {

    private static final Logger log = LoggerFactory.getLogger(RequestContextUtil.class);

    /**
     * 获取当前 HttpServletRequest
     *
     * @return 当前请求的 HttpServletRequest
     * @throws RuntimeException 如果非 Web 上下文无法获取 Request
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前 HttpServletResponse
     *
     * @return 当前请求的 HttpServletResponse
     * @throws RuntimeException 如果非 Web 上下文无法获取 Response
     */
    public static HttpServletResponse getCurrentResponse() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /**
     * 获取 ServletRequestAttributes
     *
     * @return 当前线程绑定的 ServletRequestAttributes
     * @throws RuntimeException 如果非 Web 上下文或未绑定 RequestAttributes
     */
    private static ServletRequestAttributes getServletRequestAttributes() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                throw new IllegalStateException("RequestAttributes is null");
            }
            return (ServletRequestAttributes) requestAttributes;
        } catch (Exception e) {
            log.error(">>> 非Web上下文无法获取 RequestAttributes：", e);
            throw new RuntimeException("非Web上下文无法获取 RequestAttributes", e);
        }
    }
}
